import { VxeUI } from 'vxe-pc-ui';
import router from '@/router';
import { useRoute } from 'vue-router';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { useComponentState } from '@/composables/useComponentState';
import { useTableResize } from '@/composables/useTableResize';
import { hasAuth } from '@/plugins/permission';
import { useTagsViewStore } from '@/store';
import { useVxeGridUtils } from '@/composables/useVxeGridUtils';

export const useTable = (options) => {
  const {
    API, // 后端API
    FieldAPI, // 字段API
    tableId, // 表格ID
    customConfig = {}, // 自定义配置
  } = options;

  // 表格引用
  const gridRef = ref(); // vxe-grid 组件实例
  const gridOptions = ref({}); // vxe-grid 配置
  const gridEvents = ref({}); // vxe-grid 事件

  // 附属组件引用和状态
  const addRef = ref(); // 新增
  const settingRef = ref(); // 设置

  // 公共变量
  const selectOption = ref({}); // 选择框字典数据
  const showSearch = ref(false); // 是否显示搜索表单
  const {
    isLayoutDisabled, // 布局禁用状态
    isSelectionMode, // 弹窗或者跳转组件的选择模式
    isCheckboxMode, // 多选模式
    isChildrenMode, // 子组件模式
  } = useComponentState();
  const {
    tableHeight, // 表格高度
    formItemSpan, // 表单项栅格
  } = useTableResize(isLayoutDisabled);

  // 路由相关
  const route = useRoute(); // 当前路由
  const tagsViewStore = useTagsViewStore(); // 标签页
  const utils = useVxeGridUtils(); // 相关工具函数
  const { renderToolbarButton, renderToolbarTool } = useVxeGridUtils(); // 渲染工具栏按钮

  // 选中的行数
  const selectedCount = computed(() => {
    const checkboxCount = gridRef.value?.getCheckboxRecords().length;
    const radioCount = gridRef.value?.getRadioRecord() ? 1 : 0;
    const count =
      checkboxCount == 0 ? (radioCount == 0 ? 0 : radioCount) : checkboxCount;
    return count;
  });

  // 获取选中的行
  const selectedRows = computed(() => {
    const checkboxRows = gridRef.value?.getCheckboxRecords();
    const radioRow = gridRef.value?.getRadioRecord();
    const rows = checkboxRows.length > 0 ? checkboxRows : [radioRow];
    return rows;
  });

  // 当前行数据
  const currentRow = computed(() => {
    return selectedRows.value[0];
  });

  /**
   * 方法定义
   * @returns
   */
  const useAction = () => {
    return {
      // add
      addHandle() {
        addRef.value?.show();
      },
      // setting
      settingHandle(row) {
        if (!row || !row.id) {
          settingRef.value.show();
        } else {
          settingRef.value.show(row.key);
        }
      },
      // delete
      deleteHandle(params) {
        const rows = Array.isArray(params) ? params : [params];
        const ids = rows.map((item) => item.id);
        const confirmMessage = $t('common.message.confirm.general', {
          default: '您确定要执行',
          params: {
            action: $t('common.action.delete', '删除'),
          },
        });
        const content = `${confirmMessage} ：${ids.join(', ')}`;
        VxeUI.modal.confirm(content).then((result) => {
          if (result === 'confirm') {
            API.delete({ id: ids }).then(() => {
              gridRef.value.commitProxy('query');
            });
          }
        });
      },
    };
  };

  /**
   * 定义列
   * @returns
   */
  const useColumn = () => {
    const actions = useAction();
    // 字段列
    const fieldColumn = computed(() => [
      {
        field: 'id',
        title: '编号',
        align: 'left',
        visible: false,
        showOverflow: 'tooltip',
      },
      {
        field: 'pid',
        title: $t('common.field.pid', '所属ID'),
        visible: false,
        align: 'left',
      },
      {
        field: 'segment',
        title: $t('menu.admin.lang.field.segment', '键名'),
        align: 'left',
        treeNode: true,
      },
      {
        field: 'key',
        title: $t('menu.admin.lang.field.key', '全名'),
        align: 'left',
      },
      {
        field: 'value',
        title: $t('menu.admin.lang.field.value', '键值'),
        align: 'left',
      },
      {
        field: 'lang_code',
        title: $t('menu.admin.lang.field.code', '语言'),
        align: 'center',
        cellRender: {
          name: 'RaDictSelectRender',
          code: 'sys_lang_options',
        },
        width: 'auto',
      },
      {
        field: 'sort',
        title: $t('common.field.sort', '排序号'),
        width: 'auto',
        dragSort: hasAuth('admin:i18n:drag'),
      },
      {
        field: 'status',
        title: $t('common.field.status', '状态'),
        align: 'center',
        editRender: {
          enabled: hasAuth('admin:i18n:modify'),
          name: 'RaDictSwitchRender',
          code: 'status_options',
        },
        width: 'auto',
      },

      // 结束
    ]);
    // 操作列
    const actionButtons = [
      {
        content: $t('common.action.delete', '删除'),
        type: 'danger',
        icon: 'Delete',
        text: true,
        visible: hasAuth('admin:i18n:delete'),
        onClick: (row) => actions.deleteHandle(row),
      },
      {
        content: $t('common.action.setting', '设置'),
        type: 'primary',
        icon: 'Setting',
        text: true,
        visible: hasAuth('admin:i18n:setting'),
        onClick: (row) => actions.settingHandle(row),
      },

      // 结束
    ];
    const actionColumn = [
      {
        field: 'operation',
        title: $t('common.field.operation', '操作栏'),
        width: 100 * actionButtons.length,
        align: 'center',
        fixed: 'right',
        visible: true,
        cellRender: {
          name: 'RaElButtonSetRender',
          buttons: actionButtons,
        },
      },
    ];
    // 使用 computed 属性来响应式地合并列配置
    const mergedColumns = computed(() => {
      let selectType = 'radio';
      if (isSelectionMode.value && !isCheckboxMode.value) {
        selectType = 'radio';
      }
      const selectionColumn = [
        { field: 'selection', type: selectType, width: 50, align: 'center' },
      ];

      if (isSelectionMode.value) {
        return [...selectionColumn, ...fieldColumn.value];
      } else {
        return [...selectionColumn, ...fieldColumn.value, ...actionColumn];
      }
    });
    return mergedColumns;
  };

  /**
   * 表单配置
   *
   * @returns
   */
  const useFormConfig = () => {
    // 前端搜索字段配置
    const frontendData = {
      keyword: null,
      code: null,
      status: null,
    };
    // 前端搜索字段配置
    const frontendItems = computed(() => [
      {
        field: 'keyword',
        title: $t('common.field.keyword', '关键字'),
        folding: true,
        resetValue: null,
        itemRender: {
          name: 'ElInput',
          props: {
            placeholder: $p('common.field.keyword', '关键字'),
          },
        },
      },
      {
        field: 'lang_code',
        title: $t('menu.admin.lang.field.code', '语言代码'),
        folding: true,
        resetValue: null,
        itemRender: {
          name: 'RaDictSelectRender',
          code: 'sys_lang_options',
          props: {
            placeholder: $p('menu.admin.lang.field.code', '语言代码', 'select'),
          },
        },
      },
      {
        field: 'status',
        title: $t('common.field.status', '状态'),
        resetValue: null,
        folding: true,
        itemRender: {
          name: 'RaDictSelectRender',
          code: 'status_options',
          placeholder: $p('common.field.status', '状态', 'select'),
          clearable: true,
        },
      },

      // 结束
    ]);

    // 最终提供给组件的 formConfig，使用 computed 保证响应式
    const formConfig = computed(() => {
      return {
        span: formItemSpan.value,
        collapseStatus: showSearch.value,
        titleOverflow: true,
        titleBold: true,
        data: frontendData,
        items: frontendItems.value,
      };
    });
    return frontendItems.value.length > 0 ? formConfig : {};
  };

  /**
   * 工具栏配置
   *
   * @returns
   */
  const useToolbarConfig = () => {
    // 工具栏左侧按钮
    const buttons = [
      {
        name: $t('common.action.back', '返回'),
        code: 'return_code',
        status: 'info',
        icon: 'Back',
        visible: computed(() => {
          return isChildrenMode.value;
        }),
      },
      {
        name: $t('common.action.add', '添加'),
        code: 'add_code',
        status: 'success',
        icon: 'Plus',
        visible: hasAuth('admin:i18n:add'),
      },
      {
        name: $t('common.action.delete', '删除'),
        code: 'delete_code',
        status: 'danger',
        icon: 'Delete',
        visible: hasAuth('admin:i18n:delete'),
        disabled: computed(() => {
          return selectedCount.value === 0;
        }),
      },
      {
        name: $t('common.action.setting', '设置'),
        code: 'setting_code',
        status: 'primary',
        icon: 'setting',
        visible: hasAuth('admin:i18n:setting'),
        disabled: computed(() => {
          if (currentRow.value?.value === null) return true;
          return false;
        }),
      },

      // 结束
    ];
    // 工具栏右侧按钮
    const tools = [
      {
        code: 'submit_code',
        name: $t('common.action.search', '搜索'),
        status: 'primary',
        icon: 'Search',
      },
      {
        code: 'reset_code',
        name: $t('common.action.reset', '重置'),
        status: 'info',
        icon: 'Refresh',
      },
    ];
    // 显示和隐藏搜索栏
    const showSearchtools = [
      {
        code: 'search_code',
        circle: true,
        icon: computed(() => {
          return showSearch.value ? 'vxe-icon-arrow-down' : 'vxe-icon-arrow-up';
        }),
      },
    ];
    const getToolbarConfig = () => {
      const toolbarConfig = {
        refresh: true,
        zoom: true,
        custom: true,
        buttons: renderToolbarButton(buttons),
        tools: [...renderToolbarTool(tools), ...showSearchtools],
      };
      return isSelectionMode.value ? {} : toolbarConfig;
    };
    return { getToolbarConfig };
  };

  /**
   * 事件配置
   *
   * @returns
   */
  const useGridEvents = () => {
    const actions = useAction();
    const events = {
      // 左侧工具栏按钮点击事件
      toolbarButtonClick(params) {
        switch (params.code) {
          case 'return_code':
            utils.previousHandle(tagsViewStore, route, router);
            break;
          case 'add_code':
            actions.addHandle();
            break;
          case 'delete_code':
            actions.deleteHandle(selectedRows);
            break;
          case 'setting_code':
            actions.settingHandle(selectedRows[0]);
            break;
        }
      },
      // 右侧工具栏点击事件
      toolbarToolClick(params) {
        switch (params.code) {
          case 'search_code':
            showSearch.value = !showSearch.value;
            break;
          case 'submit_code':
            gridRef.value.commitProxy('query');
            break;
          case 'reset_code':
            gridRef.value.commitProxy('initial');
            break;
        }
      },
      // 行拖拽排序
      async rowDragend(event) {
        const params = utils.getDragParams(event, gridRef.value, 'sort');
        try {
          await API.drag(params);
          gridRef.value.commitProxy('query');
        } catch (error) {
          console.error('Drag sort failed:', error);
        }
      },
      // 单元格编辑关闭事件，实现单元格编辑保存功能
      async editClosed({ row, column }) {
        try {
          await API.modify({
            id: row.id,
            field: column.field,
            value: row[column.field],
          });
          ElMessage.success('操作成功');
        } catch (error) {
          console.error('Edit closed failed:', error);
        }
      },

      // 单选框点选后,增加向父窗口传递参数
      radioChange({ row }) {
        utils.radioChangeHandle(row, route);
      },

      // 复选框点选后,增加向父窗口传递参数
      checkboxChange({ records }) {
        utils.checkBoxChangeHandle(records, route);
      },

      // 复选框的全选,增加向父窗口传递参数
      checkboxAll({ records }) {
        utils.checkBoxChangeHandle(records, route);
      },
    };
    return { getGridEvents: async () => events };
  };

  /**
   * 代理配置
   *
   * @returns
   */
  const useProxyConfig = () => {
    const getProxyConfig = async () => {
      return {
        sort: true,
        form: true,
        // page: true,
        filter: true,
        response: {
          list: 'data',
          // result: 'data',
          // total: 'total',
        },
        ajax: {
          async query({ page, form, sorts, filters }) {
            // 合并表单参数和URL参数
            const queryParams = { ...form, ...route.query };
            // 排序参数
            if (sorts.length > 0) {
              queryParams.order_by = sorts
                .map((item) => `${item.field}|${item.order}`)
                .join(',');
            }
            // 分页参数
            // if (page) {
            //   queryParams.page_size = page.pageSize;
            //   queryParams.current_page = page.currentPage;
            // }
            // 过滤参数
            if (filters) {
              filters.map((item) => {
                queryParams[item.field] = item.values;
              });
            }
            try {
              const { data: result } = await API.index(queryParams);
              if (result.sort) {
                const sortRules = Object.entries(result.sort).map(
                  ([field, order]) => ({ field, order: order.toLowerCase() }),
                );
                gridRef.value.setSort(sortRules);
              }
              return result;
            } catch (error) {
              console.error('data loading failed:', error);
              throw error;
            }
          },
        },
      };
    };

    return { getProxyConfig };
  };

  /**
   * 主要配置函数
   */
  const columns = useColumn(); // 列配置
  const formConfig = useFormConfig(); // 表单配置
  const { getToolbarConfig } = useToolbarConfig(); // 工具栏配置
  const { getProxyConfig } = useProxyConfig(); // 代理配置
  const { getGridEvents } = useGridEvents(); // 表格事件
  // 获取表格配置
  const getGridConfig = async () => {
    const options = {
      id: tableId,
      height: tableHeight,
      border: true,
      keepSource: false,
      rowConfig: {
        useKey: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
        drag: true,
      },
      columnConfig: {
        resizable: true,
      },
      resizableConfig: {
        dragMode: 'fixed',
        isDblclickAutoWidth: true,
        minWidth: 60,
      },
      customConfig: {
        storage: true,
      },
      editConfig: {
        trigger: 'dblclick',
        mode: 'cell',
        showStatus: false,
      },
      printConfig: {
        excludeFields: ['selection', 'operation'],
      },
      filterConfig: {
        remote: true,
      },
      sortConfig: {
        remote: true,
      },
      columns,
      formConfig,
      toolbarConfig: getToolbarConfig(),
      proxyConfig: await getProxyConfig(),
      // 合并自定义配置
      ...customConfig,
    };
    // 事件
    const events = await getGridEvents();
    // 返回表格配置和事件
    return { options, events };
  };

  // 初始化表格
  const initTable = async () => {
    try {
      const { data } = await FieldAPI.getOptions();
      selectOption.value = data;
      const config = await getGridConfig();
      gridOptions.value = config.options;
      gridEvents.value = config.events;
    } catch (error) {
      console.error('vxe-grid initialization failed', error);
    }
  };

  return {
    // 表格引用和配置
    gridRef,
    gridOptions,
    gridEvents,
    // 附属组件的引用
    addRef,
    settingRef,
    // 选择组件选项
    selectOption,
    // 初始化方法
    initTable,
  };
};
